<template>
  <div class="container">
    <div class="main">
      <div class="addBtn">
        <div class="searchPart">
          <a-input v-model:value="searchName" style="width: 200px; margin-right: 20px; text-align: left" placeholder="请输入要查询的站点名" />
          <a-button type="primary" @click="searchDataByName" large>
            查询
          </a-button>
        </div>
        <a-button type="danger" @click="multipleDelete" style="margin-right: 50px">
          批量删除
        </a-button>
        <a-button type="primary" @click="handleAdd" large> 新增 </a-button>
      </div>
      <a-spin size="large" v-if="loadingState" class="controlLoading"></a-spin>
      <a-table :rowKey="(record) => record.key" :columns="columns" :data-source="data" :row-selection="rowSelection" bordered :pagination="{
          pageSize: 8,
          total: totalNum,
          onChange: (pageNumber) => {
            page = pageNumber;
            getTableData(false, pageNumber);
          },
        }">
        <!-- 根据edit的状态来决定是否为可编辑状态 -->
        <template v-for="(col, index) in ['name', 'longitude', 'latitude', 'operation']" :slot="col" slot-scope="text, record">
          <div :key="index">
            <a-input v-if="record.editable" style="margin: -5px 0" :value="text" @change="(e) => handleChange(e.target.value, record.key, col)" />
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>
        <!-- 操作栏 -->
        <template slot="operation" slot-scope="text, record">
          <div class="editable-row-operations">
            <span v-if="record.editable">
              <a @click="() => save(record.key)">保存</a>
              <a-popconfirm title="取消修改?" @confirm="() => cancel(record.key)" okText="确认" cancelText="取消">
                <a>取消</a>
              </a-popconfirm>
            </span>
            <span v-else>
              <a :disabled="editingKey !== ''" @click="() => edit(record.key)">编辑</a>
              <a :disabled="editingKey !== ''" @click="() => deleteData(record.key)">删除</a>
            </span>
          </div>
        </template>
      </a-table>

      <a-modal v-model="visible" title="新增记录" @ok="handleOk" @cancel="closeModal" cancelText="取消" okText="确认">
        <div class="inputCollection">
          <div class="inputItem">
            <span style="width: 120px">雨量站点名:</span>
            <a-input v-model="addMessage.name" placeholder="请输入雨量站点名" id="name" />
          </div>
          <div class="inputItem">
            <span style="width: 50px">经度:</span>
            <a-input v-model="addMessage.longitude" placeholder="请输入经度" id="longitude" />
          </div>
          <div class="inputItem">
            <span style="width: 50px">纬度:</span>
            <a-input v-model="addMessage.latitude" placeholder="请输入纬度" id="latitude" />
          </div>
        </div>
      </a-modal>
    </div>
  </div>
</template>
<script>
const columns = [
  {
    title: "雨量站点名",
    dataIndex: "name",
    width: "23%",
    scopedSlots: { customRender: "name" },
  },
  {
    title: "经度",
    dataIndex: "longitude",
    width: "23%",
    scopedSlots: { customRender: "longitude" },
  },
  {
    title: "纬度",
    dataIndex: "latitude",
    width: "24%",
    scopedSlots: { customRender: "latitude" },
  },

  {
    title: "操作",
    dataIndex: "operation",
    width: "24%",
    scopedSlots: { customRender: "operation" },
  },
];
const data = [];
var selectedList = [];
const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(
      `selectedRowKeys: ${selectedRowKeys}`,
      "selectedRows: ",
      selectedRows
    );
  },
  onSelect: (record, selected, selectedRows) => {
    console.log("onSelect", record);
    console.log("selected", selected);
    console.log("selectedRows", selectedRows);
    selectedList = selectedRows;
  },
  onSelectAll: (selected, selectedRows, changeRows) => {
    console.log(selected, selectedRows, changeRows);
    selectedList = selectedRows;
  },
};
export default {
  data() {
    this.cacheData = data.map((item) => ({ ...item }));
    return {
      loadingState: false,
      rowSelection,
      page: 1,
      totalNum: 0,
      size: 8,
      searchName: "",
      addMessage: {
        name: "",
        longitude: "",
        latitude: "",
      },
      selectRow: [],
      data,
      columns,
      editingKey: "",
      visible: false,
    };
  },
  created() {
    sessionStorage.setItem("active", JSON.stringify(["2"]));
    this.getTableData();
  },
  methods: {
    // 获取数据
    async getTableData() {
      this.startLoading();
      const { data: res } = await this.$http.get(
        `/api/admin/rainfallstation/page?page=${this.page}&size=${this.size}`
      );
      // 则往后添加元素
      let tmp = [];
      this.totalNum = Number(res.data.total);
      res.data.records.forEach((item) => {
        tmp.push({
          key: item.id,
          name: item.name,
          longitude: item.longitude,
          latitude: item.latitude,
          systemic:item.systemic
        });
      });
      this.data = tmp;
      this.closeLoading();
      this.cacheData = this.data.map((item) => ({ ...item }));
    },
    // 批量删除
    async multipleDelete() {
      this.CancelEditState();
      this.startLoading();
      let ids = [];
      selectedList.map((item) => {
        ids.push(item.key);
      });
      console.log(ids);
      if (ids.length == 0) {
        this.common.notify("warning", "未选中数据");
        this.closeLoading();
        return;
      }
      const { data: res } = await this.$http.delete("/api/admin/rainfallstations", {
        data: {
          ids,
        },
      });
      if(res.code!=200){
        this.common.notify("warning", res.msg);
      }else{
        this.common.notify("success", "批量删除成功");
      }
      this.closeLoading();
      this.getTableData();
    },
    // 删除记录
    async deleteData(key) {
      this.startLoading();
      const newData = [...this.data];
      const index = newData.findIndex((item) => key === item.key);
      console.log("index", index);
      let id = newData[index].key;
      const { data: res } = await this.$http.delete("/api/admin/rainfallstations", {
        data: {
          ids: [id],
        },
      });
       if(res.code!=200){
        this.common.notify("warning", res.msg);
      }else{
        this.common.notify("success", "删除成功");
      }
      this.closeLoading();
      this.getTableData();
    },
    // 点击新增
    handleAdd() {
      this.CancelEditState();
      this.visible = true;
    },
    // 点击确认 新增
    async handleOk() {
      this.startLoading();
      this.visible = false;
      const { data: res } = await this.$http.post("/api/admin/rainfallstation", {
        ...this.addMessage,
      });
      console.log("111",res.code)
       if(res.code!=200){
        this.common.notify("warning", res.msg);
      }else{
        this.common.notify("success", "新增成功");
      }
      // console.log(res);
        (this.addMessage.name = ""),
        (this.addMessage.longitude = ""),
        (this.addMessage.latitude = "");
      this.closeLoading();
      this.getTableData();
    },
    // 当输入框的内容变化时,  立即将内容更新到 data中
    // 找到这一行(target)  然后设置value
    handleChange(value, key, column) {
      const newData = [...this.data];
      const target = newData.find((item) => key === item.key);
      if (target) {
        target[column] = value;
        this.data = newData;
      }
    },
    edit(key) {
      console.log("edit", key);
      const newData = [...this.data];
      // 找到这个元素
      const target = newData.find((item) => key === item.key);
      this.editingKey = key;
      // 若这个元素存在 则开启这一栏(key)
      // 进入编辑状态 并将状态同步到表格数据data中-->触发重新渲染表格 最后将input框渲染出来
      if (target) {
        target.editable = true;
        this.data = newData;
      }
    },
    // 找到这一行 将新值 覆盖旧值cacheData 设置editingKey为0
    async save(key) {
      this.startLoading();
      const newData = [...this.data];
      const newCacheData = [...this.cacheData];
      const target = newData.find((item) => key === item.key);
      const targetCache = newCacheData.find((item) => key === item.key);
      if (target && targetCache) {
        delete target.editable;
        this.data = newData;
        Object.assign(targetCache, target);
        this.cacheData = newCacheData;
      }
      console.log("target", target, targetCache);

      let tmp = target;
      target.id = tmp.key;
      delete tmp.key;
      delete tmp.systemic;
      const { data: res } = await this.$http.put("/api/admin/rainfallstation", {
        ...tmp,
      });
      if(res.code!=200){
        this.common.notify("warning", res.msg);
      }else{
        this.common.notify("success", "修改成功");
      }
      this.closeLoading();
      this.getTableData();
      this.editingKey = "";
    },
    // 查询
    async searchDataByName() {
      this.CancelEditState()
      this.startLoading();
      // 如果是为空 则请求列表
      if (this.searchName == "") {
        this.getTableData();
        return;
      }
      const { data: res } = await this.$http.get(
        `/api/admin/rainfallstation/page?name=${this.searchName}`
      );
      let currentItem = res.data.records;
      currentItem.key = currentItem.id;
      delete currentItem.id;
      this.data = [...currentItem];
      this.closeLoading();
    },
    // get的params  和 直接在路径上写 是一样的
    // 将cacheData 找到原有的数据 根据key 复制回去
    cancel(key) {
      const newData = [...this.data];
      const target = newData.find((item) => key === item.key);
      this.editingKey = "";
      if (target) {
        Object.assign(
          target,
          this.cacheData.find((item) => key === item.key)
        );
        delete target.editable;
        this.data = newData;
      }
    },
    // 点击新增弹窗的取消按钮
    closeModal() {
      (this.addMessage.name = ""),
        (this.addMessage.longitude = ""),
        (this.addMessage.latitude = "");
    },
    startLoading() {
      this.loadingState = true;
    },
    closeLoading() {
      this.loadingState = false;
    },
    CancelEditState(){
      this.editingKey = "";
       const newData = [...this.data].map(item=>{
         console.log(item)
          delete item.editable
          return item
       });
       this.data = newData
    }
  },
};
</script>
<style scoped>
.main {
  /* overflow: scroll; */
  border-radius: 10px;
  padding: 10px 40px;
  margin-top: 40px;
  background-color: #fff;
}
.editable-row-operations a {
  margin-right: 8px;
}
.container {
  overflow: scroll;
  height: calc(100vh - 50px);
  /* margin-top: 50px; */
  background-color: #eef1f2;
  padding: 0 50px 0 50px;
}
.addBtn {
  display: flex;
  justify-content: right;
  margin: 30px 0;
}
.searchPart {
  display: flex;
  flex: 1;
  justify-content: flex-start;
}
.ant-layout,
.ant-layout * {
  text-align: center;
}
.controlLoading {
  position: absolute;
  transform: translate(-50%, -50%);
  left: 50%;
  top: 50%;
}
div /deep/ .ant-table-pagination.ant-pagination {
  margin-top: 60px;
}
div /deep/ .ant-table-bordered .ant-table-thead > tr > th,
.ant-table-bordered .ant-table-tbody > tr > td {
  text-align: center;
}
.inputCollection {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-content: center;
}
.inputItem {
  display: flex;
  align-items: center;
  width: 350px;
  margin-bottom: 30px;
}
</style>
